package com.czy.owner.ui.login;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.czy.owner.R;
import com.czy.owner.db.UserHelper;
import com.czy.owner.global.Constants;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.net.utils.MyLoadView;
import com.czy.owner.permission.Acp;
import com.czy.owner.permission.AcpListener;
import com.czy.owner.permission.AcpOptions;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.BaseFragment;
import com.czy.owner.ui.MainActivity;
import com.czy.owner.ui.hotshop.GoodsDetailActivity;
import com.czy.owner.utils.ActivityHelper;
import com.czy.owner.utils.GetDeviceId;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.widget.MyEditText;
import com.easemob.cases.MessageHelper;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangyang on 2016/5/23.
 * 登录
 */

public class LoginBySmsFragment extends BaseFragment {
    @BindView(R.id.et_login_phone)
    MyEditText etLoginPhone;
    @BindView(R.id.et_login_verify_code)
    EditText etLoginVerifyCode;
    @BindView(R.id.tv_login_get_verify)
    TextView tvLoginGetVerify;
    @BindView(R.id.btn_now_login)
    Button btnNowLogin;
    protected MyLoadView mLoadView;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_login_by_sms;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        mLoadView = new MyLoadView(getContext(), "正在加载", true, true);
        etLoginPhone.setText((String) SharedPreferencesUtils.getParam(getActivity(), Constants.SHARED_PREFERENCES_KEY_PHONE, ""));
        etLoginPhone.setSelection(etLoginPhone.getText().toString().length());
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @OnClick(R.id.tv_now_regist)
    public void tvNowRegistOnClick(View view) {
        Intent ti = new Intent(getActivity(), RegistActivity.class);
        startActivity(ti);

    }


    //   倒计时响应事件  timer.start();
    private CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            try {
                tvLoginGetVerify.setClickable(false);// 设置不能点击
                tvLoginGetVerify.setText(millisUntilFinished / 1000 + getString(R.string.send_again));// 设置倒计时时间
                tvLoginGetVerify.setTextColor(getResources().getColor(R.color.appTipColor)); // 设置为灰色，这时是不能点击的
            } catch (Exception e) {
                Log.i("hep", e.toString());
            }

        }

        @Override
        public void onFinish() {
            tvLoginGetVerify.setText(getResources().getString(R.string.get_yanzhengma));
            tvLoginGetVerify.setClickable(true);// 重新获得点击
            tvLoginGetVerify.setTextColor(getResources().getColor(R.color.appThemeColor));

        }
    };

    //获取验证码
    @OnClick(R.id.tv_login_get_verify)
    public void setTvLoginGetVerifyOnClick(View view) {
        String phone = etLoginPhone.getText().toString().trim();
        if (!PhoneUtils.isNetworkConnected(getActivity())) {
            return;
        }


        if (TextUtils.isEmpty(phone)) {
            PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.phone_error_null));
            etLoginPhone.requestFocus();
            return;
        }

        if (!PhoneUtils.isMobileNO(phone)) {//本地验证手机格式
            PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.phone_error));
            etLoginPhone.requestFocus();
            return;
        }

        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_GET_SMS_FOR_LOGIN);
        params.addBodyParameter("phone", etLoginPhone.getText().toString().trim());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                String flag = JsonUtil.getJsonValuesString(result, "flag");
                if (flag.equals("true")) {
                    timer.start();

                } else {
                    PhoneUtils.ShowToastMessage(getActivity(), exp);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });

    }

    @OnClick(R.id.btn_now_login)
    public void btnNowLoginOnClick(View view) {
        String phone = etLoginPhone.getText().toString().trim();
        String verifyCode = etLoginVerifyCode.getText().toString().trim();

        if (!PhoneUtils.isNetworkConnected(getActivity())) {
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.phone_error_null));
            etLoginPhone.requestFocus();
            return;
        }

        if (!PhoneUtils.isMobileNO(phone)) {
            PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.phone_error));
            etLoginPhone.requestFocus();
            return;
        }

        if (verifyCode.length() == 0) {
            PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.input_yanzhengma));
            etLoginVerifyCode.requestFocus();
            return;
        }
        if ((Build.VERSION.SDK_INT >= 23)) {
            phoneStatePermissions(phone, verifyCode);
        } else {
            GetDeviceId getDeviceId = new GetDeviceId(getActivity());
            pid = getDeviceId.getCombinedId();
            MyLog.e("yang", "快捷登陆pid==" + pid);
            UserLoginApi(phone, verifyCode);
        }


    }

    public String pid = "";

    public void phoneStatePermissions(final String phone, final String verifyCode) {
        Acp.getInstance(getActivity()).request(new AcpOptions.Builder().setPermissions(Manifest.permission.READ_PHONE_STATE).build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                        GetDeviceId getDeviceId = new GetDeviceId(getActivity());
                        pid = getDeviceId.getCombinedId();
                        MyLog.e("yang", "快捷登陆pid==" + pid);
                        UserLoginApi(phone, verifyCode);
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        PhoneUtils.ShowToastMessage(getActivity(), "获取手机权限拒绝");

                    }
                });
    }


    private void UserLoginApi(final String phone, final String password) {
        btnNowLogin.setEnabled(false);
        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_LOGIN_BY_SMS_CODE);
        params.addBodyParameter("phone", phone);
        params.addBodyParameter("smsCode", password);
        params.addBodyParameter("consoleType", "mob");
        params.addBodyParameter("consoleSubType", "androidOwn");
        params.addBodyParameter("pid", pid);
        mLoadView.ShowLoadView();
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "onSuccess==" + result);
                String exp = JsonUtil.getJsonValuesString(result, "exp");
                String flag = JsonUtil.getJsonValuesString(result, "flag");
                if (flag.equals("true")) {
                    String data = JsonUtil.getJsonValuesString(result, "data");
                    UserHelper.getInstance().saveUserAuth(phone, "123456", true);
                    UserHelper.getInstance().saveUserInfo(getActivity(), data);
                    UserHelper.getInstance().setIsLogined(true);

                    SharedPreferencesUtils.setParam(getActivity(), Constants.SHARED_PREFERENCES_KEY_PHONE, phone);
                    SharedPreferencesUtils.setParam(getActivity(), Constants.SHARED_PREFERENCES_KEY_PASSWORD, "");

                    MessageHelper.getInstance().reset();
                    EMClient.getInstance().login(UserHelper.getInstance().getUserInfoModel(getActivity()).getImKey(), UserHelper.getInstance().getUserInfoModel(getActivity()).getImPasswd(), new EMCallBack() {//回调
                        @Override
                        public void onSuccess() {
                            MessageHelper.getInstance().getUserProfileManager().setCurrentUser(UserHelper.getInstance().getUserInfoModel(getActivity()).getNickName(),
                                    UserHelper.getInstance().getUserInfoModel(getActivity()).getUserLogo());

                            EMClient.getInstance().groupManager().loadAllGroups();
                            EMClient.getInstance().chatManager().loadAllConversations();
                            MyLog.e("yang", "登录聊天服务器成功！");
                            ActivityHelper.getInstance().finishAllActivity();
                            Intent ti = new Intent(getActivity(), MainActivity.class);
                            ti.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(ti);

                        }

                        @Override
                        public void onProgress(int progress, String status) {

                        }

                        @Override
                        public void onError(int code, String message) {
                            MyLog.e("yang", "登录聊天服务器失败！" + code + "|" + message);
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    btnNowLogin.setEnabled(true);

                                }
                            });
                            ActivityHelper.getInstance().finishAllActivity();
                            Intent ti = new Intent(getActivity(), MainActivity.class);
                            ti.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(ti);
                        }
                    });
                } else {
                    PhoneUtils.ShowToastMessage(getActivity(), exp);
                    btnNowLogin.setEnabled(true);
                    mLoadView.CancleLoadView();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                PhoneUtils.ShowToastMessage(getActivity(), getString(R.string.connect_service_error));
                ex.printStackTrace();
                MyLog.e("yang", "ex====" + ex.toString());
                btnNowLogin.setEnabled(true);
                mLoadView.CancleLoadView();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {


            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }



}
